//
//  FeedBackViewController.m
//  gpos_app
//
//  Created by 崔航飞 on 2018/8/15.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "FeedBackViewController.h"
#import "Masonry.h"
#import "WKProgressHUD.h"
#import "GPosAPI.h"
#import "SVProgressHUD.h"
@interface FeedBackViewController ()<UIGestureRecognizerDelegate,UITextViewDelegate>
@property (nonatomic,strong) UIView *backgroundViews;
@property (nonatomic,strong) UIView *viewOne;
@property (nonatomic,strong) UIView *viewTwo;
@property (nonatomic,strong) UIView *viewThree;
@property (nonatomic,strong) UIView *viewFour;
@property (nonatomic,strong) UIImageView *backOutView;
@property (nonatomic,strong) UIButton *askBtn;
@property (nonatomic,strong) UIButton *segistBtn;
@property (nonatomic,strong) UIButton *otherBtn;
@property (nonatomic,strong) UITextField *meesgeField;
@property (nonatomic,strong) UITextField *otherField;
@property (nonatomic,strong) UILabel *textNumLab;
@property (nonatomic,strong) UITextView *inputTextView;
@property (nonatomic,strong) UILabel *placeHolderLab;
//定义中间按钮变量
@property (strong,nonatomic) UIButton * tmpBtn;
@property (strong,nonatomic) WKProgressHUD *hud;
@end
#define MAX_LIMIT_NUMS 100
@implementation FeedBackViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=NO;
    //去掉返回的文字
    self.navigationController.navigationBar.topItem.title = @"";
    self.navigationItem.title=@"意见反馈";
    
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=[UIColor blackColor];
    [self initUI];
}
-(void)initUI{
    
    self.backgroundViews=[[UIView alloc] init];
    self.backgroundViews.backgroundColor=[UIColor colorWithWhite:0.94 alpha:1];
    [self.view addSubview:self.backgroundViews];
    [self.backgroundViews mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).offset(kNavbarHeight);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.height.equalTo(@(KmainScreenHeiht - kNavbarHeight - kBottomSafeHeight));
        
    }];
    
    self.viewOne = [[UIView alloc] init];
    self.viewOne.backgroundColor = [UIColor whiteColor];
    [self.backgroundViews addSubview:self.viewOne];
    [self.viewOne mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.backgroundViews.mas_top).offset(10);
        make.left.equalTo(self.backgroundViews.mas_left);
        make.right.equalTo(self.backgroundViews.mas_right);
        make.height.equalTo(@(80));
    }];
    
    UILabel *feedLab=[[UILabel alloc] init];
    feedLab.text = @"您的反馈是 :";
    feedLab.textColor = [UIColor blackColor];
    [self.viewOne addSubview:feedLab];
    [feedLab mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.viewOne.mas_top).offset(8);
        make.left.equalTo(self.viewOne.mas_left).offset(15);
        make.right.equalTo(self.viewOne.mas_right).offset(-20);
        make.height.equalTo(@(20));
        
    }];
    self.segistBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.segistBtn.tag=100;
    [self.segistBtn setImage:[UIImage imageNamed:@"icon_xz_h"] forState:UIControlStateNormal];
    
    [self.segistBtn setImage:[UIImage imageNamed:@"icon_xz_l"] forState:UIControlStateSelected];
    self.segistBtn.selected =YES;
    [self.segistBtn addTarget:self action:@selector(changeBackView:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOne addSubview:self.segistBtn];
    [self.segistBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(feedLab.mas_top).offset(32);
        make.left.equalTo(self.viewOne.mas_left).offset(15);
    }];
    
    
    
    self.askBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.askBtn.tag=101;
    [self.askBtn setImage:[UIImage imageNamed:@"icon_xz_h"] forState:UIControlStateNormal];
    [self.askBtn setImage:[UIImage imageNamed:@"icon_xz_l"] forState:UIControlStateSelected];
    [self.askBtn addTarget:self action:@selector(changeBackView:) forControlEvents:UIControlEventTouchUpInside];

    [self.viewOne addSubview:self.askBtn];
    [self.askBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(feedLab.mas_top).offset(32);
        make.left.equalTo(self.segistBtn.mas_left).offset(90);

    }];
    
    self.otherBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.otherBtn.tag=102;
    [self.otherBtn setImage:[UIImage imageNamed:@"icon_xz_h"] forState:UIControlStateNormal];
    [self.otherBtn setImage:[UIImage imageNamed:@"icon_xz_l"] forState:UIControlStateSelected];

    [self.otherBtn addTarget:self action:@selector(changeBackView:) forControlEvents:UIControlEventTouchUpInside];

    [self.viewOne addSubview:self.otherBtn];
    [self.otherBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(feedLab.mas_top).offset(32);
        make.left.equalTo(self.askBtn.mas_left).offset(90);

    }];
    
    UILabel *sergistLab=[[UILabel alloc] init];
    sergistLab.text=@"咨询";
    [self.viewOne addSubview:sergistLab];
    [sergistLab mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(feedLab.mas_top).offset(32);
        make.left.equalTo(self.segistBtn.mas_right).offset(8);
        make.right.equalTo(self.askBtn.mas_left).offset(-5);
        make.height.equalTo(@(20));

    }];

    UILabel *askLab=[[UILabel alloc] init];
    askLab.text=@"建议";
    [self.viewOne addSubview:askLab];
    [askLab mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(feedLab.mas_top).offset(32);
        make.left.equalTo(self.askBtn.mas_right).offset(8);
        make.right.equalTo(self.otherBtn.mas_left).offset(-5);
        make.height.equalTo(@(20));

    }];
    UILabel *otherLab=[[UILabel alloc] init];
    otherLab.text=@"其他";
    [self.viewOne addSubview:otherLab];
    [otherLab mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(feedLab.mas_top).offset(32);
        make.left.equalTo(self.otherBtn.mas_right).offset(8);
        make.width.equalTo(@(60));
        make.height.equalTo(@(20));

    }];

    self.viewTwo = [[UIView alloc] init];
    self.viewTwo.backgroundColor = [UIColor whiteColor];
    [self.backgroundViews addSubview:self.viewTwo];
    [self.viewTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewOne.mas_bottom).offset(10);
        make.left.equalTo(self.backgroundViews.mas_left);
        make.right.equalTo(self.backgroundViews.mas_right);
        make.height.equalTo(@(160));
    }];
    
    
    self.viewThree = [[UIView alloc] init];
    self.viewThree.backgroundColor = [UIColor whiteColor];
    [self.backgroundViews addSubview:self.viewThree];
    [self.viewThree mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewTwo.mas_bottom).offset(10);
        make.left.equalTo(self.backgroundViews.mas_left);
        make.right.equalTo(self.backgroundViews.mas_right);
        make.height.equalTo(@(50));
    }];
   
    
    UILabel *messageLab = [[UILabel alloc] init];
    messageLab.text = @"邮箱(选填):";
    [self.viewThree addSubview:messageLab];
    [messageLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewThree.mas_top).offset(12);
        make.left.equalTo(self.viewThree.mas_left).offset(15);
        make.bottom.equalTo(self.viewThree.mas_bottom).offset(-12);
        make.width.equalTo(@(100));
        
    }];
    
    self.meesgeField = [[UITextField alloc] init];
    self.meesgeField.placeholder = @"以便我们给您回复";
    [self.viewThree addSubview:self.meesgeField];
    [self.meesgeField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewThree.mas_top).offset(12);
        make.left.equalTo(messageLab.mas_right).offset(2);
        make.right.equalTo(self.viewThree.mas_right).offset(-2);
        make.bottom.equalTo(self.viewThree.mas_bottom).offset(-12);
        
    }];
    
    self.viewFour = [[UIView alloc] init];
    self.viewFour.backgroundColor = [UIColor whiteColor];
    [self.backgroundViews addSubview:self.viewFour];
    [self.viewFour mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewThree.mas_bottom).offset(10);
        make.left.equalTo(self.backgroundViews.mas_left);
        make.right.equalTo(self.backgroundViews.mas_right);
        make.height.equalTo(@(50));
    }];
    
    UILabel *otherLabs = [[UILabel alloc] init];
    otherLabs.text = @"其他(选填):";
    [self.viewFour addSubview:otherLabs];
    [otherLabs mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewFour.mas_top).offset(12);
        make.left.equalTo(self.viewFour.mas_left).offset(15);
        make.bottom.equalTo(self.viewFour.mas_bottom).offset(-12);
        make.width.equalTo(@(100));
        
    }];
    
    self.otherField = [[UITextField alloc] init];
    self.otherField.placeholder = @"其他联系方式 (QQ或手机号)";
    [self.viewFour addSubview:self.otherField];
    [self.otherField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewFour.mas_top).offset(12);
        make.left.equalTo(otherLabs.mas_right).offset(2);
        make.right.equalTo(self.viewFour.mas_right).offset(-2);
        make.bottom.equalTo(self.viewFour.mas_bottom).offset(-12);
        
    }];
    
    UILabel *lineLab = [[UILabel alloc] init];
    lineLab.text = @"--------------------------------------------------";
    lineLab.lineBreakMode = NSLineBreakByClipping;
    lineLab.textColor =[UIColor colorWithWhite:0.7 alpha:1];
    [self.viewTwo addSubview:lineLab];
    [lineLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.viewTwo.mas_bottom).offset(-18);
        make.left.equalTo(self.viewTwo.mas_left).offset(15);
        make.right.equalTo(self.viewTwo.mas_right).offset(-15);

    }];

    //限制输入的lab
    self.textNumLab = [[UILabel alloc] init];
    self.textNumLab.textColor=[UIColor colorWithWhite:0.8 alpha:1];
    self.textNumLab.textAlignment = NSTextAlignmentRight;
    self.textNumLab.text = @"0/100";
    [self.viewTwo addSubview:self.textNumLab];
    [self.textNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(lineLab.mas_bottom).offset(-10);
        make.left.equalTo(self.viewTwo.mas_left).offset(5);
        make.right.equalTo(self.viewTwo.mas_right).offset(-7);
    }];
    
    self.inputTextView = [[UITextView alloc] init];
    self.inputTextView.delegate=self;
    [self.viewTwo addSubview:self.inputTextView];
    [self.inputTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewTwo.mas_top).offset(10);
        make.left.equalTo(self.viewTwo.mas_left).offset(10);
        make.right.equalTo(self.viewTwo.mas_right).offset(-5);
        make.bottom.equalTo(self.textNumLab.mas_top).offset(-3);
       
    }];
    
    self.placeHolderLab=[[UILabel alloc] init];
    self.placeHolderLab.text=@"您的意见与反馈是我们前进的动力";
    self.placeHolderLab.textColor=[UIColor colorWithWhite:0.7 alpha:1];
    self. placeHolderLab.font = [UIFont systemFontOfSize:13];
    [self.inputTextView addSubview:self.placeHolderLab];
    [self.placeHolderLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.inputTextView.mas_top).offset(6.5);
        make.left.equalTo(self.inputTextView.mas_left).offset(8);
        make.right.equalTo(self.inputTextView.mas_right).offset(-2);
        make.height.equalTo(@(16));
        
    }];
    
    self.backOutView =[[UIImageView alloc] init];
    self.backOutView.image=[UIImage imageNamed:@"icon_anniu_f"];
    self.backOutView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goIn:)];
    tap.delegate=self;
    [self.backOutView addGestureRecognizer:tap];
    [self.backgroundViews addSubview:self.backOutView];
    [self.backOutView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.viewFour.mas_bottom).offset(40);
        make.left.equalTo(self.backgroundViews.mas_left).offset(30);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-30);
       
        
    }];
    UILabel *backLab=[[UILabel alloc] init];
    backLab.text = @"提交";
    backLab.userInteractionEnabled =YES;
    backLab.textColor = [UIColor whiteColor];
    backLab.textAlignment = NSTextAlignmentCenter;
    [self.backOutView addSubview:backLab];
    [backLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.backOutView.mas_top).offset(30);
        make.left.equalTo(self.backOutView.mas_left);
        make.right.equalTo(self.backOutView.mas_right);
        make.height.equalTo(@(20));
    }];
    
}
//退出的点击事件
-(void)goIn:(UIGestureRecognizer *)tp{
    
    if (self.inputTextView.text.length==0)
    {
        self.hud=[WKProgressHUD popMessage:@"请填写您的宝贵意见" inView:self.view duration:1 animated:YES];
    }else{
        
        /*
         参数：userId
         参数：type
         参数：content
         参数：mail
         参数：other
         
         */
        int userId=[[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
        int type;
        if (self.askBtn.selected)
        {
           
            type=2;
        }else if (self.segistBtn.selected){
          
            type=1;
            
        }else{
            
       
            type=3;
        }
        
        if (self.meesgeField.text.length==0) {
            self.meesgeField.text=@"";
        }else if (self.otherField.text.length==0){
            
            self.otherField.text=@"";
            
        }
        __weak typeof(self) weakSelf = self;
        
        NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@(userId),@"userId",@(type),@"type",self.inputTextView.text,@"content",self.meesgeField.text,@"mail",self.otherField.text,@"other", nil];
        [GPosAPI requestFeedBacksWithParams:dic andCallback:^(id obj) {
            
            if (obj==nil)
            {
                [SVProgressHUD showErrorWithStatus:@"请求失败,请检查您的网络状态"];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
            }else{
                
                if ([[obj objectForKey:@"code"] integerValue]==200)
                {
                    
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"showMyView" object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[obj objectForKey:@"message"]];
                    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                    
                }
                
            }
            
            
        }];
        
        
    }
    
}
-(void)changeBackView:(UIButton *)btn{
    
    
    UIButton *Btn=[self.viewOne viewWithTag:100];
    Btn.selected=NO;
    if (_tmpBtn == nil){
        btn.selected = YES;
        _tmpBtn = btn;
    }
    else if (_tmpBtn !=nil && _tmpBtn == btn){
        btn.selected = YES;
        
    }
    else if (_tmpBtn!= btn && _tmpBtn!=nil){
        _tmpBtn.selected = NO;
        btn.selected = YES;
        _tmpBtn = btn;
    }


}

#pragma mark -限制病情描述输入字数(最多不超过100个字)
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //不支持系统表情的输入
    if ([[textView textInputMode] primaryLanguage]==nil||[[[textView textInputMode] primaryLanguage]isEqualToString:@"emoji"]) {
        return NO;
    }
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    //获取高亮部分内容
    //NSString * selectedtext = [textView textInRange:selectedRange];
    //如果有高亮且当前字数开始位置小于最大限制时允许输入
    if (selectedRange && pos) {
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        NSRange offsetRange =NSMakeRange(startOffset, endOffset - startOffset);
        if (offsetRange.location <MAX_LIMIT_NUMS) {
            return YES;
        }else{
            return NO;
        }
    }
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger caninputlen =MAX_LIMIT_NUMS - comcatstr.length;
    if (caninputlen >=0){
        return YES;
    }else{
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        if (rg.length >0){
            NSString *s =@"";
            //判断是否只普通的字符或asc码(对于中文和表情返回NO)
            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
            if (asc) {
                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
            }else{
                __block NSInteger idx =0;
                __block NSString  *trimString =@"";//截取出的字串
                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个
                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                                         options:NSStringEnumerationByComposedCharacterSequences
                                      usingBlock: ^(NSString* substring,NSRange substringRange,NSRange enclosingRange,BOOL* stop) {
                                          if (idx >= rg.length) {
                                              *stop =YES;//取出所需要就break，提高效率
                                              return ;
                                          }
                                          trimString = [trimString stringByAppendingString:substring];
                                          idx++;
                                      }];
                s = trimString;
            }
            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
            [textView setText:[textView.text  stringByReplacingCharactersInRange:range withString:s]];
            
            //既然是超出部分截取了，哪一定是最大限制了。
            self.textNumLab.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
        }
        return NO;
    }
}

#pragma mark -显示当前可输入字数/总字数
- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView.text.length==0) {
        
        self.placeHolderLab.hidden=NO;
        
    }else{
       
        self.placeHolderLab.hidden=YES;
        
    }
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    //如果在变化中是高亮部分在变，就不要计算字符了
    if (selectedRange && pos) {
        return;
    }
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    if (existTextNum >MAX_LIMIT_NUMS){
        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
        [textView setText:s];
    }
    //不让显示负数
    self.textNumLab.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
